import { Request, Response } from "express";
import { ModelUser } from "../models/ModelUser";
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'

const JWT_SECRET = '10D0DAC871AD017C42B994A7579E2B2F'
const TOKEN_EXPIRATION = '15d'

export const register = async (req: Request, resp: Response) => {
    const { username, password } = req.body
    const existedUser = await ModelUser.findOne({ username })
    if (existedUser) {
        return resp.status(400).json({ message: 'Username already exists' })
    }

    const hashedPwd = await bcrypt.hash(password, 10)
    const user = new ModelUser({ username, password: hashedPwd })
    await user.save()

    const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: TOKEN_EXPIRATION })
    resp.json({ token })
}

export const login = async (req: Request, resp: Response) => {
    const { username, password } = req.body
    const user = await ModelUser.findOne({ username })
    if (!user || !await bcrypt.compare(password, user.password)) {
        return resp.sendStatus(401).json({ message: 'User not exist or password increet' })
    }

    const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: TOKEN_EXPIRATION })
    resp.json({ token })
}